# -*- coding: utf-8 -*-
import oss2, uuid
import yaml
import os
from oss2 import SizedFileAdapter, determine_part_size
from oss2.models import PartInfo
import sys
def percentage(consumed_bytes, total_bytes):
    if total_bytes:
        rate = int(100 * (float(consumed_bytes) / float(total_bytes)))
        print('\r{0}% '.format(rate), end='')
        sys.stdout.flush()
class AliyunOss(object):

    def __init__(self):
        yaml_file = "./config/aliyun.yaml"
        fs = open(yaml_file,encoding="UTF-8")
        datas = yaml.safe_load(fs)
        self.access_key_id = datas['access_key_id']
        self.access_key_secret = datas['access_key_secret']
        self.auth = oss2.Auth(self.access_key_id, self.access_key_secret)
        self.bucket_name = datas['bucket_name']
        self.endpoint = datas['endpoint']
        self.bucket = oss2.Bucket(self.auth, self.endpoint, self.bucket_name)
    def percentage(self,consumed_bytes, total_bytes):
        if total_bytes:
            rate = int(100 * (float(consumed_bytes) / float(total_bytes)))
            print('\r{0}% '.format(rate), end='')
            sys.stdout.flush()

    def put_file(self, name, file):
        """
        :param name: 文件名
        :param file: 文件
        :return:
        """
        # Endpoint以杭州为例，其它Region请按实际情况填写。
        result = self.bucket.put_object(name, file,progress_callback=percentage)
        # HTTP返回码。
        print('http status: {0}'.format(result.status))
        # 请求ID。请求ID是请求的唯一标识，强烈建议在程序日志中添加此参数。
        print('request_id: {0}'.format(result.request_id))
        # ETag是put_object方法返回值特有的属性。
        print('ETag: {0}'.format(result.etag))
        # HTTP响应头部。
        print('date: {0}'.format(result.headers['date']))

    def put_object_from_file(self, name, file):
        """
        上传本地文件
        :param name: 需要上传的文件名
        :param file: 本地文件名
        :return: 阿里云文件地址
        """
        result =self.bucket.put_object_from_file(name, file,progress_callback=percentage)
        if result.status == 200:
            print ('upload success')
            return "https://{}.{}/{}".format(self.bucket_name, self.endpoint, name)

        else:
            print ('upload fail,error code', result.status)
            return False
    def put_object(self, name, file):
        # 上传二进制文件
        self.bucket.put_object(name, file,progress_callback=percentage)
        return "https://{}.{}/{}".format(self.bucket_name, self.endpoint, name)